#!/usr/bin/python

import sys
import os
import logging
import collections
import xml.etree.ElementTree as xml
from cStringIO import StringIO
import subprocess

# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../lib')))
# from qt import *
try:
    sys.path.append('/mnt/jiuqian_tools/lib/')
except:
    pass

from PySide2 import QtGui, QtWidgets, QtCore
import pyside2uic as pysideuic
# from PySide2.shiboken2 import wrapInstance

logging.Logger.manager.loggerDict["pyside2uic.uiparser"].setLevel(logging.CRITICAL)
logging.Logger.manager.loggerDict["pyside2uic.properties"].setLevel(logging.CRITICAL)


def loadUiType(uiFile):
    parsed = xml.parse(uiFile)
    widget_class = parsed.find('widget').get('class')
    form_class = parsed.find('class').text

    with open(uiFile, 'r') as f:
        o = StringIO()
        frame = {}

        pysideuic.compileUi(f, o, indent=0)
        pyc = compile(o.getvalue(), '<string>', 'exec')
        exec pyc in frame

        # Fetch the base_class and form class based on their type in the xml from designer
        form_class = frame['Ui_%s' % form_class]
        base_class = getattr(QtWidgets, widget_class)
    return form_class, base_class


# ui_file = u'%s/ui/dsScenegraphXML_export.ui' %os.path.dirname(__file__)
ui_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ui', 'dsScenegraphXML_export.ui')
form, base = loadUiType(ui_file)
class MainWindow(form, base):
    def __init__(self, parent=None):

        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

        # self.setWindowIcon(QtGui.QIcon(':/deltaStudio/logo_16X16.png'))

        self.resize(350, 450)

        # self.output_frm.setVisible(False)

        # self.proc = QtCore.QProcess(self)
        # self.proc.readyReadStandardOutput.connect(lambda process=self.proc: self.normalOutputWritten(process))
        # self.proc.closeWriteChannel()
        # self.proc.setReadChannel(QtCore.QProcess.StandardOutput)


        self.mode_rdbc = QtWidgets.QButtonGroup()

        self.mode_rdbc.addButton(self.lookdev_rdb)

        self.mode_rdbc.addButton(self.shot_rdb)

        self.shot_rdb.setChecked(True)

        self.runMode_rdbc = QtWidgets.QButtonGroup()

        self.runMode_rdbc.addButton(self.localRun_rdb)

        self.runMode_rdbc.addButton(self.remoteRun_rdb)

        self.localRun_rdb.setChecked(True)

        self.files_lst = DropListWidget()

        self.dropList_lay.insertWidget(0, self.files_lst)

        self.outputFolder_lne.setText(os.path.expanduser('~'))


        self.mode = None

        self.outputFolder = self.outputFolder_lne.text()

        self.isSubmit = None

        self.frameRange = [1, 1]


        #
        self.browes_btn.clicked.connect(self.openDialog)

        self.mode_rdbc.buttonClicked.connect(self.setMode)

        self.outputFolder_lne.textChanged.connect(self.setOutFolder)

        self.run_btn.clicked.connect(self.run)

        self.useSceneRange_chk.toggled.connect(self.setRange)

        self.customRange_lne.textChanged.connect(self.setRange)


    # def normalOutputWritten(self, process):
    #
    #     self.output_txt.setText(str(process.readAllStandardOutput()))
    # def getOutputPath(self):
    #     value = os.path.expanduser('~')
    #     path = value + '/.jq_tools.env'
    #     if not os.path.exists(path):
    #         os.mknod(path)
    #         with open(path, 'a') as fhandle:
    #             fhandle.write(value)
    #         return value

    def openDialog(self):

        dir = self.outputFolder

        options = QtWidgets.QFileDialog.ShowDirsOnly


        folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Output folder: ", dir, options)

        if folder:

            self.outputFolder_lne.setText(folder)

            self.setOutFolder()



    def setMode(self):

        if self.mode_rdbc.checkedButton() == self.lookdev_rdb:

            self.mode = 'lookdev'

        else:

            self.mode = 'shot'


    def setOutFolder(self):

        self.outputFolder = self.outputFolder_lne.text()


    def setRange(self):

        if self.useSceneRange_chk.isChecked():

            customRange = self.customRange_lne.text().split('-')

            if len(customRange) > 1:

                self.frameRange = [f for f in customRange]


    def run(self):

        self.setMode()

        if self.localRun_rdb.isChecked():

            print 'Run on local.'

            for f in self.files_lst.files():

                cmdString = '%s %s/dsScenegraphXML_export.py' %('/usr/autodesk/maya/bin/mayapy', os.path.dirname(__file__))

                if self.useSceneRange_chk.isChecked():

                    cmdString += ' %s %s %s %s %s' %(f, self.outputFolder, self.mode, self.frameRange[0], self.frameRange[1])

                else:

                    cmdString += ' %s %s %s ' % (f, self.outputFolder, self.mode)

                # print cmdString
                subprocess.Popen(cmdString, shell=True)
        else:

            self.isSubmit = self.submitFile_chk.isChecked()

            print 'Run on remote.'


# class EmittingStream(QtCore.QObject):
#
#     textWritten = QtCore.Signal(str)
#
#     def write(self, text):
#
#         self.textWritten.emit(str(text))


class DropListWidget(QtWidgets.QListWidget):

    def __init__(self, parent=None):

        super(DropListWidget, self).__init__(parent)

        self.setAcceptDrops(True)

        self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)

        self.setAlternatingRowColors(True)

        #
        self.paths = {}


    def keyReleaseEvent(self, event):

        if event.key() == QtCore.Qt.Key_Delete:

            for item in self.selectedItems():

                try:

                    self.takeItem(self.row(item))

                    del self.paths[item.text()]

                except:

                    pass


    def dragEnterEvent(self, event):

        event.acceptProposedAction()


    def dragMoveEvent(self, event):

        pass


    def dropEvent(self, event):

        mimeData = event.mimeData()

        if mimeData.hasUrls():

            for url in mimeData.urls():

                path_str = url.toLocalFile()

                if os.path.splitext(path_str)[1] in ['.ma', '.mb']:

                    self.paths[os.path.basename(path_str)] = path_str

        self.updateList()


    def updateList(self):

        self.paths = sortedDict(self.paths)

        self.clear()

        self.addItems(self.paths.keys())


    def files(self):

        return self.paths.values()


def sortedDict(dic):

    return collections.OrderedDict(sorted(dic.items()))



if __name__ == '__main__':

    app = QtWidgets.QApplication.instance()

    if not app:

        app = QtWidgets.QApplication([])

    win = MainWindow()

    win.show()

    win.raise_()
    try:

        sys.exit(app.exec_())

    except:

        pass
    # app.exec_()
